package com.amaake.rpc.registry.controller;

import com.amaake.rpc.client.Proxy;
import com.amaake.rpc.registry.AmaakeRpcProxyMap;
import com.amaake.rpc.registry.RpcLoginInterceptor;
import com.amaake.rpc.registry.RpcRegLoginBean;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;

import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Amaake
 * \* Date: 2016/11/20 0020
 * \* Time: 21:48
 * \* Description: 春眠不觉晓，起来敲代码。
 * \
 */
@Before(RpcLoginInterceptor.class)
public class RpcServiceController extends Controller {

    public void index(){
        renderJsp("/rpc/index.jsp");
    }

    public void rpchome(){
        Map<String, Proxy> proxyMap = AmaakeRpcProxyMap.proxyMap;
        setAttr("map",proxyMap);
        renderJsp("/rpc/rpchome.jsp");
    }

    public void quit(){
        StringBuffer url = getRequest().getRequestURL();
        String tempContextUrl = url.delete(url.length() - getRequest().getRequestURI().length(), url.length())
                .append(getRequest().getServletContext().getContextPath()).toString();
        removeSessionAttr("rpcloginsession");
        String json = "{\n" +
                "  \"referer\": \""+tempContextUrl+"/rpc"+"\",\n" +
                "  \"state\": \"success\",\n" +
                "  \"message\": \"退出成功\"\n" +
                "}";
        renderJson(json);
    }

    @Clear
    public void login(){
        StringBuffer url = getRequest().getRequestURL();
        String tempContextUrl = url.delete(url.length() - getRequest().getRequestURI().length(), url.length())
                .append(getRequest().getServletContext().getContextPath()).toString();
        String username = getPara("username");
        String password = getPara("password");
        RpcRegLoginBean rpcRegLoginBean = AmaakeRpcProxyMap.rpcRegLoginBean;
        String json = "";
        if(username.equals(rpcRegLoginBean.getUsername())&&password.equals(rpcRegLoginBean.getPassword())){
            setSessionAttr("rpcloginsession",rpcRegLoginBean);
            json = "{\n" +
                    "  \"referer\": \""+tempContextUrl+"/rpc"+"\",\n" +
                    "  \"state\": \"success\",\n" +
                    "  \"message\": \"登陆成功\"\n" +
                    "}";
        }else{
            json = "{\n" +
                    "  \"referer\": \""+tempContextUrl+"/rpc"+"\",\n" +
                    "  \"state\": \"error\",\n" +
                    "  \"message\": \"登陆失败\"\n" +
                    "}";
        }
        renderJson(json);
    }

}